<?php

namespace app\common\helper;

use app\common\model\Goods;
use app\common\model\Log;
use app\common\model\MoneyLog;
use app\common\model\User;
use app\index\controller\Product;
use GuzzleHttp\Client;
use think\Exception;

class DouYinHelper
{
    protected $pid;
    protected $key;
    protected $dou_key;
    protected $api_base;
    protected $appKey;
    protected $appSecret;
    public function __construct() {
        $config = cache('config');
        $this->pid = $config['dou_pid'];
        $this->key = $config['dou_key'];
        $this->dou_key = $config['dou_key2'];
        $this->api_base = "https://openapi-fxg.jinritemai.com";
    }
    
    /**
     * @param $page
     * @param $limit
     * @param $start_time
     * @param $end_time
     * @return mixed|void
     * @throws \GuzzleHttp\Exception\GuzzleException
     * author 小李子 2023-11-07 09:16
     * description 订单列表   API运行   搁置不用，请使用下面的计划任务
     */
    public function getOrderList($page= 0,$limit= 200,$start_time = null,$end_time= null)
    {
        $url = "http://api.web.ecapi.cn/douyin/getDoukeOrderAds";
        $param = [
            "apkey" => $this->key,
            "size" => $limit,
            "start_time" => $start_time,
            "end_time" => $end_time,
            "cursor" => $page,
            "pid" => $this->pid,
            "dou_key" => $this->dou_key,
            "time_type" => 'pay'
        ];
        try {
            $client = new Client();
            $result = $client->get($url . "?" . http_build_query($param));
            $result = json_decode($result->getBody()->getContents(),true);
            if ($result['code'] == 200) {
                $orders = $result['data']['orders'];
                file_put_contents("task.txt",count($result['data']) . "\r\n",FILE_APPEND);
                foreach ($orders as $item) {
                    $exit = Log::where("order_no",$item['pid_info']['external_info'])->find();
                    if ($exit) {
                        if ($exit->flow_point !== $item['flow_point'] && $item['flow_point'] == 'PAY_SUCC') {
                            $exit->flow_point = 'PAY_SUCC';
                            $exit->status = 1;
                            $user = User::where("id",$exit->user_id)->find();
                            if ($user) {
                                $user->money += $exit->next_money;
                                $user->save();
                            }
                            MoneyLog::create([
                                "user_id" => $user->id,
                                "money" => $exit->next_money,
                                "is_add" => 1,
                                "content" => "返佣"
                            ]);
                        }
                        if ($exit->flow_point !== $item['flow_point'] && $item['flow_point'] == 'REFUND') {
                            $exit->flow_point = 'REFUND';
                            $exit->status = -2;
    
                            $user = User::where("id",$exit->user_id)->find();
                            if ($user) {
                                $user->money -= $exit->next_money;
                                $user->save();
                            }
                            MoneyLog::create([
                                "user_id" => $user->id,
                                "money" => $exit->next_money,
                                "is_add" => 0,
                                "content" => "退款扣佣"
                            ]);
                        }
                        $exit->order_id = $item['order_id'];
                        $exit->pay_time = strtotime($item['pay_success_time']);
                        $exit->total_pay_amount = round($item['total_pay_amount'] / 100,2);
                        $exit->save();
                    }
                }
                return $result["data"]['orders'];
            } else {
                throwError($result);
            }
        } catch (Exception $exception) {
            throwError($exception->getMessage());
        }
    }
    
    /**
     * @param $page
     * @param $limit
     * @param $start_time
     * @param $end_time
     * @return mixed|void
     * @throws \GuzzleHttp\Exception\GuzzleException
     * author 小李子 2023-11-07 09:16
     * description 订单列表  命令行运行
     */
    public function getOrderListCmd($page= 0,$limit= 200,$start_time = null,$end_time= null)
    {
        $url = "http://api.web.ecapi.cn/douyin/getDoukeOrderAds";
        $param = [
            "apkey" => $this->key,
            "size" => $limit,
            "start_time" => $start_time,
            "end_time" => $end_time,
            "cursor" => $page,
            "pid" => $this->pid,
            "dou_key" => $this->dou_key,
            "time_type" => 'pay'
        ];
        try {
            $client = new Client();
            $result = $client->get($url . "?" . http_build_query($param));
            $result = json_decode($result->getBody()->getContents(),true);
            if ($result['code'] == 200) {
                $orders = $result['data']['orders'];
                foreach ($orders  as $item) {
                    $exit = Log::where("order_no",$item['pid_info']['external_info'])->find();
                    if ($exit) {
                        if ($exit->flow_point !== $item['flow_point'] && $item['flow_point'] == 'PAY_SUCC') {
                            $goods = Goods::where("id",$exit->goods_id)->find();
                            if ($goods) {
                                if ($goods->stock > 0) {
                                    $goods->stock--;
                                    $goods->save();
                                }
                            }
                            $exit->flow_point = 'PAY_SUCC';
                            $exit->status = 1;// 已经下单 待返佣
                            queue("app\common\job\DouYin@fan",$exit->toArray(),3600*24*3);
                        }
                        if ($exit->flow_point !== $item['flow_point'] && $item['flow_point'] == 'REFUND') {
                            $exit->flow_point = 'REFUND';
                            $exit->status = -2; //码失效
                            $user = User::where("id",$exit->user_id)->find();
                            if ($user) {
                                $user->money -= $exit->next_money;
                                $user->save();
                            }
                            MoneyLog::create([
                                "user_id" => $user->id,
                                "money" => $exit->next_money,
                                "is_add" => 0,
                                "content" => "退款扣佣"
                            ]);
                        }
                        $exit->order_id = $item['order_id'];
                        $exit->pay_time = strtotime($item['pay_success_time']);
                        $exit->total_pay_amount = round($item['total_pay_amount'] / 100,2);
                        $exit->save();
                    }
                }
                echo "处理" . count($orders) . '条数据-' . date("Y-m-d H:i:s") . "\r\n";
            } else {
                echo '出错误' . date("Y-m-d H:i:s") . "\r\n";
            }
        } catch (Exception $exception) {
            echo $exception->getMessage() . date("Y-m-d H:i:s") . "\r\n";
        }
    }
    
    
    /**
     * @param $product_url string    抖音产品链接
     * @param $external_info string  自定义产品
     * @return mixed|void
     * @throws \GuzzleHttp\Exception\GuzzleException
     * author 小李子 2023-11-07 09:14
     * description 转链
     */
    public function translateUrl(string $product_url, string $external_info)
    {
        $url = "http://api.web.ecapi.cn/douyin/getKolProductsShare";
        $client = new Client();
        $param = [
            "apkey" => $this->key,
            "product_url" => $product_url,
            "external_info" => $external_info,
            "pid" => $this->pid,
            "dou_key" => $this->dou_key
        ];
        $ul = $url . "?" . http_build_query($param);
        $result = $client->get($ul);
        $result = json_decode($result->getBody()->getContents(),true);
        if ($result['code'] == 200) {
            if (!empty($result['data']['dy_password'])) {
                return $result["data"]["dy_password"];
            } else {
                throwError($result["data"]);
            }
        } else {
            throwError($result);
        }
    }
    
    
    
    public function douTranslateUrl($product_url,$external_info)
    {
    
    }
    
    
    public function send($method,$paramJson)
    {
        $client = new Client();
        $timestamp = time();
        $base_param = [
            "method" => urlencode($method),
            "app_key" => urlencode($this->appKey),
            "access_token" => "",
            "param_json" => json_encode($paramJson,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
        ];
    }
    
    // 计算签名
    protected function sign(string $method, int $timestamp, string $paramJson): string {
        $paramPattern = 'app_key' . $this->appKey . 'method' . $method . 'param_json' . $paramJson . 'timestamp' . $timestamp . 'v2';
        $signPattern = $this->appSecret . $paramPattern . $this->appSecret ;
        
        print('sign_pattern:' . $signPattern . "\n");
        return hash_hmac("sha256", $signPattern, $this->appSecret );
    }
    
    
    // 序列化参数，入参必须为关联数组
    protected function marshal(array $param): string {
        $this->rec_ksort($param); // 对关联数组中的kv，执行排序，需要递归
        $s = json_encode($param, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); // 重新序列化，确保所有key按字典序排序
        // 加入flag，确保斜杠不被escape，汉字不被escape
        return $s;
    }

// 关联数组排序，递归
    protected function rec_ksort(array &$arr) {
        $kstring = true;
        foreach ($arr as $k => &$v) {
            if (!is_string($k)) {
                $kstring = false;
            }
            if (is_array($v)) {
                $this->rec_ksort($v);
            }
        }
        if ($kstring) {
            ksort($arr);
        }
    }
}